package com.kcht.np.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kcht.np.entity.SysPermission;
import com.kcht.np.entity.SysRole;
import com.kcht.np.entity.SysUser;
import com.kcht.np.common.jwt.JwtUser;
import com.kcht.np.service.SysPermissionService;
import com.kcht.np.service.SysRoleService;
import com.kcht.np.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * spring security 认证 UserDetailsService 实现类
 * </p>
 *
 * @Package:        com.kcht.np.mp.service.impl
 * @Description:    spring security 认证 UserDetailsService 实现类
 * @Author:         liuqi
 * @CreateDate:     2020/3/31 21:24
 */

@Slf4j
@Service("JwtUserDetailsServiceImpl")
public class JwtUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", username));
        if (user == null || StringUtils.isEmpty(user.getUid())) {
            throw new UsernameNotFoundException("用户已被删除");
        } else {
            // 权限
            Set<SysPermission> allPermByUserId = sysPermissionService.findPermissionByUserId(user.getUid());
            List<String> authorities = allPermByUserId.stream()
                    .map(SysPermission::getResources)
                    .collect(Collectors.toList());
            // 角色
            final Set<SysRole> allRoleByUserId = sysRoleService.findRolesByUserId(user.getUid());
            allRoleByUserId.forEach((SysRole role) -> {
                authorities.add(role.getRoleName());
            });
            return new JwtUser(user.getUid(), user.getUsername(), user.getPassword(), user.getStatus(), authorities);
        }
    }
}
